package com.wt.admin.service.sys.impl;


import com.aizuda.easy.security.code.BasicCode;
import com.aizuda.easy.security.util.LocalUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wt.admin.code.sys.SysRoleCode;
import com.wt.admin.domain.entity.sys.SysMenuEntity;
import com.wt.admin.domain.entity.sys.SysRoleEntity;
import com.wt.admin.domain.vo.sys.SysRoleListVO;
import com.wt.admin.domain.vo.sys.SysRoleVO;
import com.wt.admin.domain.vo.sys.UserVO;
import com.wt.admin.mapper.sys.SysRoleMapper;
import com.wt.admin.service.sys.SysMenuService;
import com.wt.admin.service.sys.SysRoleService;
import com.wt.admin.util.AssertUtil;
import com.wt.admin.util.PageUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRoleEntity> implements SysRoleService {

    @Resource
    private SysRoleMapper sysRoleMapper;
    @Resource
    private SysMenuService sysMenuService;

    @Override
    public SysRoleVO findRoleId(Integer roleId) {
        SysRoleEntity sysRoleEntity = sysRoleMapper.selectById(roleId);
        AssertUtil.objIsNull(sysRoleEntity, SysRoleCode.ROLE_CODE_1100);
        AssertUtil.Boolean.isFalse(sysRoleEntity.getEnableTag(),SysRoleCode.ROLE_CODE_1100);
        List<SysMenuEntity> menus = sysMenuService.findMenu(sysRoleEntity.getMenuIds(),false);
        AssertUtil.objIsNull(sysRoleEntity,SysRoleCode.ROLE_CODE_1101);
        SysRoleVO sysRoleVO = new SysRoleVO();
        sysRoleVO.setName(sysRoleEntity.getRoleName());
        sysRoleVO.setMenus(menus);
        return sysRoleVO;
    }

    @Override
    public SysRoleListVO find(PageUtil.PageDTO<SysRoleEntity> data) {
        AssertUtil.objIsNull(data.getData(), BasicCode.BASIC_CODE_99998);
        SysRoleListVO sysRoleListVO = new SysRoleListVO();
        // 查询角色列表
        UserVO userVO = LocalUtil.getUser();
        PageUtil.PageVO<SysRoleEntity> pag = PageUtil
                .findPage(data, (page) -> sysRoleMapper.find(page, userVO.getId()));
        sysRoleListVO.setPage(pag);
        // 查询权限转tree
        List<SysMenuEntity> sysMenuEntities = sysMenuService.find(new SysMenuEntity());
        sysRoleListVO.setMenus(sysMenuEntities);
        return sysRoleListVO;
    }


    @Override
    public SysRoleEntity edit(SysRoleEntity data) {
        AssertUtil.Str.isEmpty(data.getRoleName(), SysRoleCode.ROLE_CODE_1102);
        AssertUtil.List.isEmpty(data.getMenuIds()   , SysRoleCode.ROLE_CODE_1103);
        saveOrUpdate(data);
        return data;
    }

    @Override
    public SysRoleEntity del(SysRoleEntity data) {
        AssertUtil.Str.isEmpty(data.getRoleName(), BasicCode.BASIC_CODE_99998);
        sysRoleMapper.deleteById(data.getId());
        return null;
    }

    @Override
    public List<SysRoleEntity> findAll() {
        return sysRoleMapper.selectAll();
    }

}
